//
//  AddCustomerCell.m
//  KuWoCan
//
//  Created by LiBenCan on 17/9/26.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "AddCustomerCell.h"
#import "ChinaPlckerView.h"
#import <CoreLocation/CoreLocation.h>
//  Country(国家)  State(省)  City（市） SubLocality(区)
#define kLocation_State @"State"
#define kLocation_City @"City"
#define kLocation_SubLocality @"SubLocality"

@interface AddCustomerCell () <ChinaPlckerViewDelegate,CLLocationManagerDelegate, UIAlertViewDelegate, UITextViewDelegate,UITextFieldDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager;

@property (nonatomic,strong) NSDictionary *addressDic;

@end

@implementation AddCustomerCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self setUpUI];
        
        [self startLocation];
        
    }
    return self;
}

-(void)startLocation{
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if ([CLLocationManager locationServicesEnabled] && !(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted))
    {
        //判断定位操作是否被允许
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        self.locationManager.distanceFilter = 10.0f;
        
        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8以上版本定位需要）
    }
    else
    {
        //提醒用户打开定位开关
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无法使用定位" message:@"请检查您的设备是否开启定位功能" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"检查下", nil];
        [alert show];
    }
    
}

#pragma CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         for (CLPlacemark * placemark in placemarks)
         {
             
             _addressDic = [placemark addressDictionary];
             
             //  Country(国家)  State(省)  City（市） SubLocality(区)
             NSLog(@"#####%@",_addressDic);
             [ChinaPlckerView customChinaPicker:self superView:[CommonTool getCurrtenViewCtrWithView:self].view defaultProName:_addressDic[kLocation_State] defaultCityName:_addressDic[kLocation_City] defaultAreaName:_addressDic[kLocation_SubLocality]];
         }
     }];
    [manager stopUpdatingLocation];
}


- (void)setUpUI
{
    UILabel *personLab = [UILabel new];
    personLab.text = @"*客户名称";
    personLab.font = KwFont(15 * screenW_6);
    [self addSubview:personLab];
    [personLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(20 * screenW_6));
        make.height.equalTo(@(15 * screenW_6));
        make.top.equalTo(@(17 * screenW_6));
        make.width.equalTo(@(80 * screenW_6));
    }];
    
    _nameTf = [UITextField new];
    _nameTf.font = KwFont(15 * screenW_6);
    _nameTf.delegate = self;
    [_nameTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _nameTf.placeholder = @"营业执照上的全称";
    [self addSubview:_nameTf];
    [_nameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(personLab.mas_right);
        make.top.equalTo(personLab);
        make.height.equalTo(personLab);
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = KwGaryColor;
    [self addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(personLab.mas_bottom).offset(15 * screenW_6);
        make.left.equalTo(personLab);
        make.height.equalTo(@1);
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    
    UILabel *teleLab = [UILabel new];
    teleLab.text = @"*联系人";
    teleLab.font = KwFont(15 * screenW_6);
    [self addSubview:teleLab];
    [teleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(personLab);
        make.top.equalTo(lineView.mas_bottom).offset(17 * screenW_6);
    }];
    
    _teleTf = [UITextField new];
    _teleTf.font = KwFont(15 * screenW_6);
    _teleTf.placeholder = @"请添加联系人";
    _teleTf.delegate = self;
    [_teleTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:_teleTf];
    [_teleTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameTf.mas_left);
        make.top.equalTo(teleLab.mas_top);
        make.height.equalTo(@(15 * screenW_6));
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    UIView *lineView1 = [UIView new];
    lineView1.backgroundColor = KwGaryColor;
    [self addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(teleLab.mas_bottom).offset(15 * screenW_6);
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(@1);
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    UILabel *lianxiLab = [UILabel new];
    lianxiLab.text = @"*联系电话";
    lianxiLab.font = KwFont(15 * screenW_6);
    [self addSubview:lianxiLab];
    [lianxiLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(personLab);
        make.top.equalTo(lineView1.mas_bottom).offset(17 * screenW_6);
    }];
    
    _lianXiTf = [UITextField new];
    _lianXiTf.font = KwFont(15 * screenW_6);
    _lianXiTf.delegate = self;
    [_lianXiTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _lianXiTf.keyboardType = UIKeyboardTypeNumberPad;
    _lianXiTf.placeholder = @"请添加联系电话";
    [self addSubview:_lianXiTf];
    [_lianXiTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameTf.mas_left);
        make.top.equalTo(lianxiLab.mas_top);
        make.height.equalTo(@(15 * screenW_6));
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    UIView *lineView2 = [UIView new];
    lineView2.backgroundColor = KwGaryColor;
    [self addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lianxiLab.mas_bottom).offset(15 * screenW_6);
        make.left.equalTo(lianxiLab.mas_left);
        make.height.equalTo(@1);
        make.right.equalTo(@(-20 * screenW_6));
    }];

    
    UILabel *banGongteleLab = [UILabel new];
    banGongteleLab.text = @"办公电话";
    banGongteleLab.font = KwFont(15 * screenW_6);
    [self addSubview:banGongteleLab];
    [banGongteleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(personLab);
        make.top.equalTo(lineView2.mas_bottom).offset(17 * screenW_6);
    }];
    
    _banPhoneTf = [UITextField new];
    _banPhoneTf.font = KwFont(15 * screenW_6);
    _banPhoneTf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _banPhoneTf.placeholder = @"请添加办公电话（选填）";
    _banPhoneTf.delegate = self;
    [_banPhoneTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:_banPhoneTf];
    [_banPhoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameTf.mas_left);
        make.top.equalTo(banGongteleLab.mas_top);
        make.height.equalTo(@(15 * screenW_6));
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    UIView *lineView3 = [UIView new];
    lineView3.backgroundColor = KwGaryColor;
    [self addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(banGongteleLab.mas_bottom).offset(15 * screenW_6);
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(@1);
        make.right.equalTo(@(-20 * screenW_6));
    }];

    
    _selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_selectBtn setImage:kImg(@"dingwei") forState:UIControlStateNormal];
    [_selectBtn setTitle:@"点击选择" forState:UIControlStateNormal];
    _selectBtn.titleLabel.font = KwFont(15 * screenW_6);
    _selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _selectBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [_selectBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_selectBtn addTarget:self action:@selector(showPicker) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_selectBtn];
    [_selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView3.mas_bottom).offset(15 * screenW_6);
        make.height.equalTo(@(15 * screenW_6));
        make.right.equalTo(@(-20 * screenW_6));
        make.left.equalTo(_nameTf.mas_left);
    }];
    
    UILabel *addressLab = [UILabel new];
    addressLab.text = @"所在区域";
    addressLab.font = KwFont(15 * screenW_6);
    [self addSubview:addressLab];
    [addressLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(personLab.mas_left);
        make.height.equalTo(@(15 * screenW_6));
        make.top.equalTo(lineView3.mas_bottom).offset(15 * screenW_6);
    }];
    
    UIView *lineView4 = [UIView new];
    lineView4.backgroundColor = KwGaryColor;
    [self addSubview:lineView4];
    [lineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_selectBtn.mas_bottom).offset(15 * screenW_6);
        make.left.equalTo(_nameTf.mas_left);
        make.height.equalTo(@1);
        make.right.equalTo(@(-20 * screenW_6));
    }];
    
    _addressTf = [UITextView new];
    //    _addressTf.backgroundColor = [UIColor greenColor];
    //    _addressTf.text = @"请输入详细地址";
    _addressTf.delegate = self;
    _addressTf.font = KwFont(15 * screenW_6);
    _addressTf.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _addressTf.scrollEnabled = NO;
    [self addSubview:_addressTf];
    [_addressTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameTf.mas_left);
        make.right.equalTo(@(-20 * screenW_6));
        make.top.equalTo(lineView4.mas_bottom).offset(15 * screenW_6);
        make.height.greaterThanOrEqualTo(@(15 * screenW_6));
        make.bottom.equalTo(@(-15 * screenW_6));
    }];
    
    // _placeholderLabel
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入内容";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [_addressTf addSubview:placeHolderLabel];
    
    // same font
    placeHolderLabel.font = [UIFont systemFontOfSize:15 * screenW_6];
    [_addressTf setValue:placeHolderLabel forKey:@"_placeholderLabel"];

    
}

- (void)showPicker
{
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if ([CLLocationManager locationServicesEnabled] && !(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted))
    {
        //判断定位操作是否被允许
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        self.locationManager.distanceFilter = 10.0f;
        
        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8以上版本定位需要）
        [self.locationManager startUpdatingLocation];
    } else {
        //提醒用户打开定位开关
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无法使用定位" message:@"请检查您的设备是否开启定位功能" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"检查下", nil];
        [alert show];
    }
}

- (void)chinaPlckerViewDelegateChinaModel:(ChinaArea *)chinaModel
{
    NSString *cityStr = [NSString stringWithFormat:@"%@%@%@",chinaModel.provinceModel.NAME,chinaModel.cityModel.NAME,chinaModel.areaModel.NAME];
    if (_block)
    {
        _block(cityStr);
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 1: {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
            break;
            
        default:
            break;
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    UITableView *tableView = [self tableView];
    [tableView beginUpdates];
    [tableView endUpdates];
    //    [self layoutIfNeeded];
}

- (UITableView *)tableView
{
    UIView *tableView = self.superview;
    
    while (![tableView isKindOfClass:[UITableView class]] && tableView) {
        tableView = tableView.superview;
    }
    
    return (UITableView *)tableView;
}

- (void)setDataDic:(NSDictionary *)dataDic
{
    _nameTf.text = [ToolViewViewController GetDataStr:dataDic[@"name"]];
    _teleTf.text = [ToolViewViewController GetDataStr:dataDic[@"clientContacts"]];
    _lianXiTf.text = [ToolViewViewController GetDataStr:dataDic[@"clientPhone"]];
    _banPhoneTf.text = [ToolViewViewController GetDataStr:dataDic[@"clientTel"]];
    [_selectBtn setTitle:[ToolViewViewController GetDataStr:dataDic[@"region"]] forState:UIControlStateNormal];
    _addressTf.text = [ToolViewViewController GetDataStr:dataDic[@"clientAddress"]];
}

-(void)textFieldDidChange:(UITextField *)textField
{
    NSString *toBeString = textField.text;
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        
        int limitNum = 0;
        if ([_nameTf isEqual:textField]) {
            limitNum = 20;
        }else if ([_teleTf isEqual:textField])
        {
            limitNum = 10;
        }
        else if ([_lianXiTf isEqual:textField])
        {
            limitNum = 11;
        }
        else if ([_banPhoneTf isEqual:textField])
        {
            limitNum = 15;
        }else
        {
            limitNum = 50;
        }

        if (toBeString.length > limitNum && limitNum!=0)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:limitNum];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:limitNum];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, limitNum)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}


@end
